using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Security;
using sbMembership.Library.Presenters.ViewInterfaces;
using sbMembership.Library.Domain;

namespace sbMembership.Library.Presenters
{
    public class ListRolesPresenter
    {
        private IListRolesView view;
        public enum ActionEnum
        {
             updated
            ,added
            ,deleted
            ,none
        }

        public ListRolesPresenter(IListRolesView view)
        {
            if (view == null) throw new ArgumentNullException("view may not be null");

            this.view = view;
        }


        public EventHandler LaunchAddRoleEvent;
        public EventHandler DeleteRoleCompleteEvent;
        public EventHandler LaunchEditRoleEvent;

        public void InitViewFor(ActionEnum action)
        {
            DisplayMessageFor(action);
            List<sbRole> roleList = new List<sbRole>();
            foreach (string roleName in Roles.GetAllRoles())
            {
                roleList.Add(new sbRole(roleName));
            }
            view.Roles = roleList;
        }

        private void DisplayMessageFor(ActionEnum action)
        {
            if (action == ActionEnum.updated)
                view.Message = "The role was successfully updated.";
            else if (action == ActionEnum.added)
                view.Message = "The role was successfully added.";
            else if (action == ActionEnum.deleted)
                view.Message = "The role was successfully deleted.";
            else
                view.Message = "Click a role's ID to edit the role.";
        }

        public void LaunchAddRole()
        {
            LaunchAddRoleEvent(this, null);
        }

        public void DeleteRole(string roleName)
        {
            if (Roles.RoleExists(roleName))
            {
                string[] users = Roles.GetUsersInRole(roleName);
                if (users.Length > 0)
                    Roles.RemoveUsersFromRole(users, roleName);
                Roles.DeleteRole(roleName);
            }
            DeleteRoleCompleteEvent(this, null);
        }

        public void LaunchEditRole(string roleName)
        {
            EditRoleEventArgs e = new EditRoleEventArgs();
            e.RoleName = roleName;
            LaunchEditRoleEvent(this, e);
        }

    }
}
